import defaultSettings from '@/settings'
import { getStorage, setStorage } from '@/utils'
import { getConfig } from '@/api/index'

const { showSettings, fixedHeader, sidebarLogo, tagsView = false, theme } = defaultSettings

const state = {
  showSettings: showSettings,
  fixedHeader: getStorage('fixedHeader') || fixedHeader,
  sidebarLogo: getStorage('sidebarLogo') || sidebarLogo,
  tagsView: getStorage('tagsView') || tagsView,
  theme: getStorage('theme') || theme,
  config: {} // 后台返回的系统配置
}

const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
      // 存入本地防止刷新丢失
      setStorage(key, value)
    }
  },
  SET_CONFIG: (state, config) => {
    state.config = config
  }
}

const actions = {
  changeSetting ({ commit }, data) {
    commit('CHANGE_SETTING', data)
  },
  async loadConfig ({ commit }) {
    const res = await getConfig()
    commit('SET_CONFIG', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
